// API 基础配置
// 后端服务运行在8000端口
const API_BASE_URL = 'http://localhost:8000';

// Toast 通知工具类
class Toast {
    static show(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `toast-enter fixed top-4 right-4 min-w-[300px] bg-white rounded-lg shadow-lg p-4 z-50 flex items-center gap-3`;
        
        let borderColor, iconName, iconColor;
        switch (type) {
            case 'success':
                borderColor = 'border-green-500';
                iconName = 'check_circle';
                iconColor = 'text-green-500';
                break;
            case 'error':
                borderColor = 'border-red-500';
                iconName = 'error';
                iconColor = 'text-red-500';
                break;
            default:
                borderColor = 'border-blue-500';
                iconName = 'info';
                iconColor = 'text-blue-500';
        }
        
        toast.classList.add('border-l-4', borderColor);
        toast.innerHTML = `
            <span class="material-symbols-outlined ${iconColor}">${iconName}</span>
            <span class="flex-1 text-gray-800">${message}</span>
        `;
        
        document.body.appendChild(toast);
        
        setTimeout(() => {
            toast.classList.remove('toast-enter');
            toast.classList.add('toast-exit');
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }
}

// Modal 对话框工具类
class Modal {
    static confirm(title, message, onConfirm) {
        const backdrop = document.createElement('div');
        backdrop.className = 'modal-backdrop fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        backdrop.innerHTML = `
            <div class="modal-content bg-white rounded-xl shadow-2xl max-w-md w-full mx-4 p-6">
                <h3 class="text-xl font-bold text-gray-800 mb-3">${title}</h3>
                <p class="text-gray-600 mb-6">${message}</p>
                <div class="flex gap-3 justify-end">
                    <button class="cancel-btn px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-100 transition">
                        取消
                    </button>
                    <button class="confirm-btn px-6 py-2 bg-red-500 text-white rounded-lg hover:shadow-lg transition">
                        确认
                    </button>
                </div>
            </div>
        `;
        
        document.body.appendChild(backdrop);
        
        const close = () => backdrop.remove();
        
        backdrop.querySelector('.cancel-btn').addEventListener('click', close);
        backdrop.querySelector('.confirm-btn').addEventListener('click', () => {
            close();
            onConfirm();
        });
        backdrop.addEventListener('click', (e) => {
            if (e.target === backdrop) close();
        });
    }
}

// API 请求工具类
class API {
    // 流式聊天接口
    static async streamChat(question, onToken, onContext, onDone, onError) {
        try {
            const response = await fetch(`${API_BASE_URL}/api/chat/stream`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ question })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let buffer = '';

            while (true) {
                const { done, value } = await reader.read();
                
                if (done) {
                    if (onDone) onDone();
                    break;
                }

                buffer += decoder.decode(value, { stream: true });
                const lines = buffer.split('\n');
                buffer = lines.pop(); // 保留不完整的行

                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        const data = line.slice(6).trim();
                        
                        if (data === '[DONE]') {
                            if (onDone) onDone();
                            return;
                        }

                        try {
                            const json = JSON.parse(data);
                            
                            if (json.type === 'context' && onContext) {
                                // 传递检索到的文本块内容和相似度
                                onContext({
                                    content: json.content,
                                    similarity: json.similarity
                                });
                            } else if (json.type === 'token' && onToken) {
                                onToken(json.content);
                            } else if (json.type === 'done' && onDone) {
                                onDone();
                            }
                        } catch (e) {
                            console.error('解析SSE数据失败:', e);
                        }
                    }
                }
            }
        } catch (error) {
            console.error('聊天请求失败:', error);
            if (onError) onError(error);
        }
    }

    // 上传文档
    static async uploadDocument(file) {
        try {
            const formData = new FormData();
            formData.append('file', file);

            const response = await fetch(`${API_BASE_URL}/api/documents/upload`, {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                const error = await response.json().catch(() => ({ detail: '上传失败' }));
                throw new Error(error.detail || '上传失败');
            }

            return await response.json();
        } catch (error) {
            console.error('上传文档失败:', error);
            // 如果是网络错误，给出更友好的提示
            if (error instanceof TypeError && error.message.includes('fetch')) {
                throw new Error('无法连接到后端服务，请确保后端正在运行');
            }
            throw error;
        }
    }

    // 获取文档列表
    static async getDocuments() {
        try {
            const response = await fetch(`${API_BASE_URL}/api/documents/`, {
                method: 'GET'
            });

            if (!response.ok) {
                if (response.status === 404) {
                    throw new Error('API接口不存在(404)');
                }
                throw new Error(`获取文档列表失败 (HTTP ${response.status})`);
            }

            return await response.json();
        } catch (error) {
            console.error('获取文档列表失败:', error);
            // 如果是网络错误，保留原始错误信息
            if (error instanceof TypeError && error.message.includes('fetch')) {
                throw new Error('Failed to fetch - 无法连接到后端服务');
            }
            throw error;
        }
    }

    // 删除文档
    static async deleteDocument(documentId) {
        try {
            const response = await fetch(`${API_BASE_URL}/api/documents/${documentId}`, {
                method: 'DELETE'
            });

            if (!response.ok) {
                const error = await response.json().catch(() => ({ detail: '删除失败' }));
                throw new Error(error.detail || '删除失败');
            }

            return await response.json();
        } catch (error) {
            console.error('删除文档失败:', error);
            // 如果是网络错误，给出更友好的提示
            if (error instanceof TypeError && error.message.includes('fetch')) {
                throw new Error('无法连接到后端服务，请确保后端正在运行');
            }
            throw error;
        }
    }
}

// 工具函数：格式化时间
function formatTime(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    
    // 小于1分钟
    if (diff < 60000) {
        return '刚刚';
    }
    // 小于1小时
    if (diff < 3600000) {
        return `${Math.floor(diff / 60000)}分钟前`;
    }
    // 小于1天
    if (diff < 86400000) {
        return `${Math.floor(diff / 3600000)}小时前`;
    }
    // 小于7天
    if (diff < 604800000) {
        return `${Math.floor(diff / 86400000)}天前`;
    }
    
    // 超过7天显示具体日期
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 工具函数：转义HTML
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 工具函数：简单的Markdown渲染
function renderMarkdown(text) {
    // 转义HTML
    let html = escapeHtml(text);
    
    // 代码块
    html = html.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, lang, code) => {
        return `<pre><code class="language-${lang || 'text'}">${code.trim()}</code></pre>`;
    });
    
    // 行内代码
    html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
    
    // 标题
    html = html.replace(/^### (.*$)/gm, '<h3>$1</h3>');
    html = html.replace(/^## (.*$)/gm, '<h2>$1</h2>');
    html = html.replace(/^# (.*$)/gm, '<h1>$1</h1>');
    
    // 粗体
    html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
    
    // 斜体
    html = html.replace(/\*(.+?)\*/g, '<em>$1</em>');
    
    // 链接
    html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');
    
    // 换行
    html = html.replace(/\n/g, '<br>');
    
    return html;
}

